<template>
  <n-upload
    :action="props.uploadUrl"
    :default-file-list="list"
    :max="1"
    :accept="props.accept"
    name="file"
    list-type="image-card"
    @finish="onUploadFinish"
  >
    点击上传
  </n-upload>
</template>

<script setup>
import { computed } from 'vue'

const props = defineProps({
  uploadUrl: {
    type: String,
    default: 'http://localhost:3000/upload'
  },
  fileList: {
    type: Array,
    default: () => []
  },
  accept: {
    type: String,
    default: 'image/*'
  }
})

const emit = defineEmits(['update:fileList'])

const list = computed({
  get: () => props.fileList,
  set: val => {
    emit('update:fileList', val)
  }
})

const onUploadFinish = ({ file, event }) => {
  console.log(event)
  const filename = file.name.split('.')[0]
  file.name = filename
  const target = JSON.parse(event?.target.response)
  console.log(target.data)
  file.url = target.data
  list.value = [file]
  return file
}
</script>

<style scoped></style>
